using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using General.Core.Data;
using General.Entities.Data;
using General.Entities.Models;
using Microsoft.EntityFrameworkCore;

namespace General.Services.DicType
{
    public class DicTypeService : IDicTypeService
    {
        private readonly IRepository<tc_dictype> tc_DictypeRepository;

        public DicTypeService(IRepository<tc_dictype> tc_dictypeRepository)
        {
            tc_DictypeRepository = tc_dictypeRepository;
        }
        
        /// <summary>
        /// 增加信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task AddInfo(tc_dictype model)
        {
            model.createtime = DateTime.Now;
            await tc_DictypeRepository.insertAsync(model);
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteInfo(string ids)
        {
            var arr = ids.Split(",",StringSplitOptions.RemoveEmptyEntries);
            var arrints = arr.Select<string, int>(x => Convert.ToInt32(x));
            var list = await tc_DictypeRepository.GetAllAsync(x=>arrints.Contains(x.id)).ToListAsync();
            return await tc_DictypeRepository.DeleteListAsync(list);
        }


        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task EditInfo(tc_dictype data)
        {
            var model = await tc_DictypeRepository.getByIdAsync(data.id);
            model.name = data.name;
            await tc_DictypeRepository.UpdateAsync(model);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<AdminResult> GetList(int page, int limit, string name)
        {
            AdminResult result = new AdminResult();
            var query = from d in tc_DictypeRepository.Table
                        orderby d.id //descending
                        select new tc_dictype() {
                            id=d.id,createtime=d.createtime,name=d.name
                        };
            if (!string.IsNullOrWhiteSpace(name))
            {
                query = query.Where(x => x.name.Contains(name));
            }
            result.count = await query.CountAsync();
            result.data = await query.Skip((page - 1) * limit).Take(limit).ToListAsync();
            result.code = 0;
            return result;
        }
    }
}